package controller;

import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import model.dao.Database;
import view.LoginView;
import view.PBoxView;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ResetController {
    public TextField account;
    public TextField email;
    public PasswordField pwd;
    public PasswordField re_pwd;
    public AnchorPane resetPane;

    /**
     * 密码找回
     * @param actionEvent
     * @throws Exception
     */
    public void reset(ActionEvent actionEvent) throws Exception {
        System.out.println("reset...");

        String ac = account.getText();
        String e = email.getText();
        String p1 = pwd.getText();
        String p2 = re_pwd.getText();

        if (ac.isEmpty()) {
            new PBoxView("请正确输入要找回密码的账号！").show();
        } else {
            if (e.isEmpty()) {
                new PBoxView("请正确输入注册时所用邮箱！").show();
            } else {
                if (!p1.isEmpty() && !p2.isEmpty() && p1.equals(p2)) {
                    Database database = new Database();
                    database.connect();
                    String sql1 = "select user_id from `user` where account = ? and email = ?";
                    ResultSet resultSet1 = database.execResult(sql1, ac, e);
                    String user_id = null;
                    if (resultSet1.next()) {
                        user_id = resultSet1.getString("user_id");
                    } else {
                        user_id = null;
                    }
                    resultSet1.close();
                    if (user_id == null) {
                        new PBoxView("没有找到对应账号哦！").show();
                    } else {
                        String sql2 = "update `user` set password = ? where user_id = ?";
                        database.exec(sql2, p1, user_id);
                        new PBoxView("操作成功！" + "\n您的账号：" + ac + "\n您的密码：" + p1).show();
                        Stage stage = (Stage) resetPane.getScene().getWindow();
                        stage.close();
                        new LoginView().show();
                    }
                } else {
                    new PBoxView("两次密码不一致！").show();
                }
            }
        }


    }

    public void cancel(ActionEvent actionEvent) throws IOException {
        Stage stage = (Stage) resetPane.getScene().getWindow();
        stage.close();
        new LoginView().show();
    }
}
